import React, { Component } from "react";
import { SafeAreaView, Text, View, Image, StatusBar, DeviceEventEmitter, Platform, BackHandler, ToastAndroid } from "react-native";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import WorkCenterPage from './WorkCenterPage'
import StrictCarListPage from './StrictCarListPage'
import OfferPriceCenterPage from './OfferPriceCenterPage'
import MessageCenterPage from './MessageCenterPage'
import MyCenterPage from './MyCenterPage'
import AndroidModule from '../../../src/utils/AndroidConnent'
import AsyncStorage from '../../utils/AsyncStorage'//本地存储
import Constant from '../../utils/Constant'//全局变量
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";

import OpenIMSDKRN, { OpenIMEmitter, MessageItem } from 'open-im-sdk-rn';
import DeviceInfo from 'react-native-device-info';
import { getImgUrl, getPerm } from '../../utils/ComFunction';
import {  PermissionType } from "../../utils/Enum";
import SeekingListPage from "../seekCenter/SeekingListPage";
import MyCarSourcePage from "./MyCarSourcePage";

const isIos = Platform.OS == 'ios';

let lastBackPressed = 0
const Tab = createBottomTabNavigator();

let route
let navigation

export default class Root extends Component {

    constructor(props) {
        super(props);

        let pricePerm = getPerm(PermissionType.Permission_EnableOfferPriceView)


        let purchaseCenterPerm = getPerm(PermissionType.Permission_EnablePurchaseCenter)

        this.state = {
            pricePerm:pricePerm,
            unreadMsgCount: 0,//未读条数
            isInHome: true,
            currentIndex:0,
            purchaseCenterPerm, // 采购权限
            isExternalCarEntryUser: Constant.userInfo.isExternalCarEntryUser || 0, // 是否是外部车辆录入用户
            viewCarCount: 0, // 未读的求购中心消息数量
            buyerId: Constant.userInfo.buyerId,
        };

        this.lastTapTime = 0;

    }

    componentDidMount() {
        if (!Constant.userInfo.imToken) {
            try {
                AndroidModule.gotoLogin({})
            } catch (error) {

            }
        }

        if (Platform.OS === 'android') {
            BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid.bind(this));
        }

        this.homeListener = DeviceEventEmitter.addListener('homeListener', (e) => {
            console.log('homeListener', e)
            this.setState({
                isInHome: e.isInHome,
                currentIndex: e.index
            })
        });


        let that = this
        this.updateUnreadMsg = DeviceEventEmitter.addListener('updateUnreadMsg', (data) => {
            setTimeout(() => {
                that.messageGetBrief()
                console.log('messageGetBrief')
            }, 1000)
        });

        this.updateViewCarCount = DeviceEventEmitter.addListener('updateViewCarCount', (data) => {
            setTimeout(() => {
                that.getUserNoViewCarCount()
            }, 1000)
        });

        setTimeout(() => {
            this.messageGetBrief()
            this.getUserNoViewCarCount()
        }, 1000);

        // 添加每N秒执行一次的定时器
        this.intervalTimer = setInterval(() => {
            this.getUserNoViewCarCount();
        }, 19000);

        this.getMerchantDetail()
        this.getMerchantMember()
        this.getInfoBySessionId()
        if(!isIos){
            this.getVersionInfo()
        }
    }

    componentWillUnmount() {
        if (this.updateUnreadMsg) {
            this.updateUnreadMsg.remove()
        }
        if (this.updateViewCarCount) {
            this.updateViewCarCount.remove()
        }
        if (this.homeListener) {
            this.homeListener.remove()
        }
        if (Platform.OS === 'android') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid.bind(this));
        }

        // 清理定时器避免内存泄漏
        if (this.intervalTimer) {
            clearInterval(this.intervalTimer);
        }

    }

    onBackAndroid() {
        if (navigation && navigation.isFocused()) {

            if (this.state.isInHome) {
                if (lastBackPressed && lastBackPressed + 2000 >= Date.now()) {
                    try {
                        AndroidModule.exitApp()
                    } catch (error) {
                        BackHandler.exitApp();
                    }

                    return;
                }
                lastBackPressed = Date.now();
                ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
                return true;
            } else {
                DeviceEventEmitter.emit('backHome', { index: this.state.currentIndex });
                return true
            }


        }
        return false;
    }

    getMerchantMember() {
        if (!Constant.userInfo.merchantId) {
            return
        }
        HttpUtils.getRequest(HttpUrls.getMerchantMember, { merchantId: Constant.userInfo.merchantId })
            .then((result) => {
                let code = result.code
                if (code == 0) {
                    let data = result.data
                    if (data) {
                        let memberClass = data.memberClass
                        Constant.userInfo.memberClass = memberClass
                    } else {
                        Constant.userInfo.memberClass = 10
                    }
                }
            })
            .catch((error) => {

            });
    }

    getMerchantDetail() {
        let params = {
            merchantId: Constant.userInfo.merchantId,
        }
        HttpUtils.getRequest(HttpUrls.getMerchantDetail, params)
            .then((result) => {
                if (result.code == 0) {
                    let data = result.data
                    Constant.userInfo.provinceName = data.provinceName
                    Constant.userInfo.cityName = data.cityName
                    Constant.userInfo.districtName = data.districtName
                    Constant.userInfo.province = data.province
                    Constant.userInfo.city = data.city
                    Constant.userInfo.district = data.district
                    Constant.userInfo.address = data.address
                    Constant.userInfo.merchantLogoPic = data.merchantLogoPic
                    Constant.userInfo.merchantPhone = data.phone
                    Constant.userInfo.isMarginMerchant = data.isMarginMerchant
                    Constant.userInfo.isScBrand = data.isScBrand
                    Constant.userInfo.authenCode = data.authenCode
                    Constant.userInfo.certifiedStatus = data.certifiedStatus
                    Constant.userInfo.lat = data.lat
                    Constant.userInfo.lon = data.lon
                    Constant.companyInfo = data
                } else {
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }
            })
            .catch((error) => {

            });
    }

    getInitRouteName(route) {
        if (route && route.params) {
            if (route.params.initialRouteName && route.params.initialRouteName != '') {
                return route.params.initialRouteName
            }
        }
        // 如果有买手身份，优先进入报价中心页面
        if(this.state.pricePerm && this.state.buyerId > 0){
            return 'OfferPriceCenterPage'
        }
        // 如果是外部车辆录入用户，默认进入我的车源页面
        if(this.state.isExternalCarEntryUser == 1){
            return 'MyCarSourcePage'
        }
        return 'WorkCenterPage'
    }

    render() {
        route = this.props.route
        navigation = this.props.navigation

        const conditionalScreens = [];
        // <Tab.Screen name="MessageCenterPage" component={MessageCenterPage} listeners={{
        //                             tabPress: e => {
        //                                 StatusBar.setBackgroundColor('#ffffff');
        //                                 StatusBar.setBarStyle('dark-content');
        //                                 console.log('tabclick', 'MessageCenterPage')
        //                                 if (this.isQuickTap()) {//快速点击
        //                                     DeviceEventEmitter.emit('scrollToUnreadMsg', {})
        //                                 }
        //                             },
        //                         }} options={{
        //                             title: '消息',
        //                             tabBarBadge: this.state.unreadMsgCount > 0 ? this.state.unreadMsgCount : null,
        //                             tabBarBadgeStyle: { backgroundColor: '#e33e33', fontSize: 8 },
        //                         }}></Tab.Screen>

        // const initialRoute = this.getInitRouteName(this.props.route);
        // console.log('Initial route set to:', initialRoute);

        if (this.state.purchaseCenterPerm) {
            conditionalScreens.push(
                <Tab.Screen
                    key="SeekingListPage"
                    name="SeekingListPage"
                    component={SeekingListPage}
                    options={{
                        title: '求购中心',
                        tabBarBadge: this.state.noViewCarCount > 0 ? this.state.noViewCarCount : null,
                        tabBarBadgeStyle: { backgroundColor: '#e33e33', fontSize: 8 },
                    }}
                />
            );
        }

        const myCarSourceScreens = [];
        if (this.state.isExternalCarEntryUser == 1) {
            myCarSourceScreens.push(
                <Tab.Screen
                    key="MyCarSourcePage"
                    name="MyCarSourcePage"
                    component={MyCarSourcePage}
                    options={{ title: '我的车源' }}
                />
            );
        }


        return (
            <View style={{ flex: 1 }}>
                <Tab.Navigator
                    onRef={(ref) => (this.tabbar = ref)}
                    initialRouteName={this.getInitRouteName(this.props.route)}
                    screenOptions={({ route }) => ({
                        tabBarIcon: ({ focused, color, size }) => {
                            let iconName;
                            if (route.name === 'WorkCenterPage') {
                                iconName = focused ? require('source/image/homePage/foot1.png') : require('source/image/homePage/foot1_hl.png');
                            }
                            // else if (route.name === 'StrictCarListPage') {
                            //     iconName = focused ? require('source/image/homePage/foot2.png') : require('source/image/homePage/foot2_hl.png');
                            // }
                            else if (route.name === 'SeekingListPage') {
                                iconName = focused ? require('source/image/homePage/foot6.png') : require('source/image/homePage/foot6_hl.png');
                            }
                            else if (route.name === 'MyCarSourcePage') {
                                iconName = focused ? require('source/image/homePage/foot6.png') : require('source/image/homePage/foot6_hl.png');
                            }
                            else if (route.name === 'OfferPriceCenterPage') {
                                iconName = focused ? require('source/image/homePage/foot3.png') : require('source/image/homePage/foot3_hl.png')
                            } else if (route.name === 'MessageCenterPage') {
                                iconName = focused ? require('source/image/homePage/foot4.png') : require('source/image/homePage/foot4_hl.png');
                            } else if (route.name === 'MyCenterPage') {
                                iconName = focused ? require('source/image/homePage/foot5.png') : require('source/image/homePage/foot5_hl.png');
                            }
                            return <Image source={iconName} style={{ width: 24, height: 24 }} />
                        },
                        headerShown: false, // This line hides the top navigation bar
                        tabBarStyle: {
                            height: isIos ? (49 + Constant.bottomHeight) : 65, // 设置底部栏高度
                        },
                    })}
                    tabBarOptions={{
                        activeBackgroundColor: '#ffffff',
                        inactiveBackgroundColor: '#ffffff',
                        activeTintColor: '#E33E33',
                        inactiveTintColor: '#333333',
                        labelStyle: {
                            fontSize: 10, // 文字大小
                        },

                    }}
                    backBehavior='none'
                >
                    {this.state.isExternalCarEntryUser == 0 && (
                        <Tab.Screen name="WorkCenterPage" component={WorkCenterPage} listeners={{
                            tabPress: e => {
                            },
                        }} options={{
                            title: '工作台',
                        }}></Tab.Screen>
                    )}

                    {/*<Tab.Screen name="StrictCarListPage" component={StrictCarListPage} listeners={{*/}
                    {/*    tabPress: e => {*/}
                    {/*    },*/}
                    {/*}} options={{*/}
                    {/*    title: '严选车源',*/}
                    {/*}}></Tab.Screen>*/}
                    {/*{this.state.pricePerm ? */}
                    {/*<Tab.Screen name="StrictCarListPage" component={StrictCarListPage} listeners={{*/}
                    {/*    tabPress: e => {*/}
                    {/*    },*/}
                    {/*}} options={{*/}
                    {/*    title: '严选车源',*/}
                    {/*}}></Tab.Screen> */}

                    {myCarSourceScreens}

                    {conditionalScreens}

                    {this.state.pricePerm > 0 && (
                        <Tab.Screen
                            name="OfferPriceCenterPage"
                            component={OfferPriceCenterPage}
                            initialParams={this.state.buyerId > 0 ? { dealStatus: 1 } : ''}
                            listeners={{
                                tabPress: e => {
                                },
                            }}
                            options={{
                                title: '报价中心',
                            }}
                        />
                    )}


                    {this.state.isExternalCarEntryUser == 0 && (
                        <Tab.Screen name="MessageCenterPage" component={MessageCenterPage} listeners={{
                            tabPress: e => {
                                StatusBar.setBackgroundColor('#ffffff');
                                StatusBar.setBarStyle('dark-content');
                                console.log('tabclick', 'MessageCenterPage')
                                if (this.isQuickTap()) {//快速点击
                                    DeviceEventEmitter.emit('scrollToUnreadMsg', {})
                                }
                            },
                        }} options={{
                            title: '消息',
                            tabBarBadge: this.state.unreadMsgCount > 0 ? this.state.unreadMsgCount : null,
                            tabBarBadgeStyle: { backgroundColor: '#e33e33', fontSize: 8 },
                        }}></Tab.Screen>
                    )}


                    <Tab.Screen name="MyCenterPage" component={MyCenterPage} listeners={{
                        tabPress: e => {
                            StatusBar.setBackgroundColor('#f9f9f9');
                            StatusBar.setBarStyle('dark-content');
                        },
                    }} options={{
                        title: '我的',
                    }}></Tab.Screen>
                </Tab.Navigator>
            </View>
        );
    }

    isQuickTap = () => {
        const now = new Date().getTime();
        const DOUBLE_TAP_DELAY = 500;
        const isQuick = now - this.lastTapTime < DOUBLE_TAP_DELAY;
        this.lastTapTime = now;
        return isQuick;
    };


    getUnreadMsgCount() {

        let params = {
            pageNo: 1,
            pageSize: 100,
            imUserId: Constant.userInfo.imUserId,
            role: Constant.userInfo.isFranchisee == 1 ? '2' : '1',
            source: 2
        }

        HttpUtils.postRequest(HttpUrls.getUserConversation, params)
            .then((result) => {


                let code = result.code
                if (code == 0) {

                    let resultList = result.data.resultList

                    if (resultList.length > 0) {

                        let unreadMsgCount = this.state.unreadMsgCount

                        resultList.map((item) => {
                            if (item.imConversationInfo && item.imConversationInfo.unreadCount > 0) {
                                unreadMsgCount += item.imConversationInfo.unreadCount
                            }
                        })

                        this.setState({
                            unreadMsgCount: unreadMsgCount
                        })

                    } else {

                    }

                } else {

                }
            })
            .catch((error) => {

            });
    }

    //统计未读的求购数量
    getUserNoViewCarCount() {
        HttpUtils.getRequest(HttpUrls.getUserNoViewCarCount, {})
            .then((result) => {
                let code = result.code
                // console.log('updateViewCarCount', result.data)
                if (code == 0) {
                    Constant.noViewSeekingCount = result.data || 0
                    this.setState({
                        noViewCarCount: result.data,
                    })
                }
            })
            .catch((error) => {

            });
    }

    messageGetBrief() {

        let params = {

        }

        HttpUtils.postRequest(HttpUrls.messageGetBrief, params)
            .then((result) => {
                let code = result.code
                if (code == 0) {
                    let data = result.data
                    let unreadCount = data.sysMsgCount + data.carInfoMsgCount + data.contractOrderCount
                    this.setState({
                        unreadMsgCount: unreadCount
                    }, function () {
                        this.getUnreadMsgCount()
                    })

                } else {
                    this.getUnreadMsgCount()
                }
            })
            .catch((error) => {
                this.getUnreadMsgCount()
            });
    }

    getInfoBySessionId() {

        let params = {
            sessionId: Constant.userInfo.sessionId,
        }

        HttpUtils.getRequest(HttpUrls.getInfoBySessionId, params)
            .then((result) => {
                let code = result.code
                if (code == 0 && result.data) {
                    console.log('getInfoBySessionId', result.data)
                    Constant.userInfo.perms = result.data.stringPerms
                    let pricePerm = getPerm(PermissionType.Permission_EnableOfferPriceView)
                    this.setState({
                        pricePerm:pricePerm
                    })
                    AndroidModule.updateUserInfo({perms:result.data.stringPerms})
                } else {

                }
            })
            .catch((error) => {

            });
    }

    getVersionInfo() {

        let params = {
            terminalType: isIos ? 15 : 14
        }

        HttpUtils.getRequest(HttpUrls.getSysVersion, params)
            .then((result) => {
                let code = result.code
                if (code == 0) {
                    if (result.data) {
                        let newversion = result.data.version.replaceAll('.', '')
                        let nowVersion = DeviceInfo.getVersion().replaceAll('.', '')
                        let isNewVersion = newversion > nowVersion ? true : false
                        if (isNewVersion) {
                            let obj = {
                                type: result.data.focreUpdate,
                                versionMsg: result.data.description,
                                downloadUrl: result.data.url
                            }
                            AndroidModule.updateDialog(obj)
                        }


                    } else {
                        this.setState({
                            versionText: false
                        })


                    }

                }
            })
            .catch((error) => {

            });
    }

};